﻿using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.RBAC;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Transactions;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.RBAC
{
    /// <summary>
    /// 修改角色权限命令处理
    /// </summary>
    public class UpdateRolePermissionCommandHandlter : IRequestHandler<UpdateRolePermissionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRep;
        private readonly IBaseRepository<RolePermissionModel> rolepermissionRep;

        public UpdateRolePermissionCommandHandlter(IBaseRepository<RoleModel> roleRep,IBaseRepository<RolePermissionModel> rolepermissionRep)
        {
            this.roleRep = roleRep;
            this.rolepermissionRep = rolepermissionRep;
        }


        public async Task<ApiResult<int>> Handle(UpdateRolePermissionCommand request, CancellationToken cancellationToken)
        {

            //分布式事务
            using(var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //查询角色
                    var role = roleRep.GetAll().AsNoTracking().FirstOrDefault(x => x.ID == request.RoleId);

                    if (role != null)
                    {
                        //修改角色
                        role.RoleName = request.RoleName;
                        role.UpdateTime = DateTime.Now;
                        await roleRep.UpdateAsync(role);
                    }

                    //查询角色权限
                    var rolepermission = rolepermissionRep.GetAll().AsNoTracking().Where(x => x.RoleId == request.RoleId).ToList();
                    //删除角色权限
                    await rolepermissionRep.DeltelAll(rolepermission);

                    //添加角色权限
                    foreach (var permissionId in request.PermissionId)
                    {

                        var model = new RolePermissionModel
                        {
                            PermissionId = permissionId,
                            RoleId = role.ID,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            IsState = true,
                            IsDeleted = false
                        };
                        await rolepermissionRep.AddAsync(model);



                    }

                    //提交事务
                    tran.Complete();

                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Dispose();


                    throw;
                }



            }

           

            return new ApiResult<int>()
            {
                code = ResultEnumCode.Ok,
                data = 1,
                 message="修改角色权限成功",

            };
        }
    }
}
